<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/3
 * Time: 14:29
 */
use think\Session;
use think\Response;
use think\Request;
use think\Url;
use think\Db;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
function index()
{

    //服务分类
    $w = array(
        'parentId'=> 0,
        'isShow'  => 1,
        'isEnable' => 1,
    );
    $list=Db::name('service_category')->where($w)->order('addDateTime','asc')->cache(false)->select();
    foreach ($list as $k1=>$v1){
        $sn=Db::name('service_category')->where('parentId',$v1['serviceCategoryId'])->order('serialNo','asc')->cache(false)->select();

        foreach ($sn as $k2=>$v2){
            $data=Db::name('service')->where('serviceCategoryId',$v2['serviceCategoryId'])->where('isForSale',1)->cache(false)->select();
            $sn[$k2]['san'] = $data;
        }
        $list[$k1]['er'] = $sn;
    }
    return  $list;

}
function category()
{
    $sc=Db::name('service_category')->where('parentId',0)->cache(false)->select();
    return $sc;
}
 function ip($type = 0, $adv = false)
{
    $type      = $type ? 1 : 0;
    static $ip = null;
    if (null !== $ip) {
        return $ip[$type];
    }

    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }
            $ip = trim(current($arr));
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? [$ip, $long] : ['0.0.0.0', 0];
    return $ip[$type];
}
//生成随机数
function autoId()
{
    $uid = think\Db::query("select concat(304,right(UUID_SHORT(),11)) as uid");
    return $uid[0]["uid"] . mt_rand(10000, 99999);
}
/**
 * 短信发送
 * @param string $templateCode 短信模板编号
 * @param string $phoneNumber 短信接收者
 * @param array $param 短信模板中字段的值
 * @param string $outId  outId 可选
 * @return stdClass
 */
function sendSms($templateCode,$phoneNumber,$param=[],$outId="")
{
    $demo = new \sms\SmsSend(
        "LTAIfYFO5KAJdJCG", //AccessKeyID
        "RURwZOUxxv9nQusYmu2uv292955Xrp" //AccessKeySecret
    );
    $response = $demo->sendSms(
        "企业宝", // 短信签名
        $templateCode,
        $phoneNumber,
        $param,
        $outId
    );
    return $response;
}
/**
 * 根据Id加密生成邀请码
 * @param $uuid  Id值
 * @return string
 */
function create_code($uuid) {
    static $source_string = 'WXG15NO6DEFUVOPJKLHI234MPQRS9ABT78CYZ';
    $num = $uuid;
    $code = '';
    while ( $num > 0) {
        $mod = $num % 35;
        $num = ($num - $mod) / 35;
        $code = $source_string[$mod].$code;
    }
    if(empty($code[3]))$code = str_pad($code,4,'0',STR_PAD_LEFT);
    return $code;
}
/**
 * 根据邀请码解密生成Id
 * @param $code 邀请码
 * @return bool|int
 */
function decode($code) {
    static $source_string = 'WXG15NO6DEFUVOPJKLHI234MPQRS9ABT78CYZ';
    if (strrpos($code, '0') !== false)$code = substr($code, strrpos($code, '0')+1);
    $len = strlen($code);
    $code = strrev($code);
    $num = 0;
    for ($i=0; $i < $len; $i++) {$num += strpos($source_string, $code[$i]) * pow(35, $i);
    }
    return $num;
}
function getPwd()
{
    $pwd=['000000','111111','888888'];
    return $pwd[mt_rand(0, 2)];
}
//根据身份标签获取该服务商id
function getProviderId ()
{
    $starLevelLink ='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];
    //截取身份标签
    $starLevelLink =  substr($starLevelLink,strpos($starLevelLink,"//")+2,strpos($starLevelLink,".")-strpos($starLevelLink,"//")-2);
    $where = array(
        'starLevelLink'=>$starLevelLink,
        'checkStatus'=>1,
    );
//    $providerId =Db::name('provider')->where($where)->value('providerId');
//   if($providerId  == null){
//   echo "<script>window.location.href='http://www.qybao.com.cn'</script>";
   $providerId="3045520567587566746";
//   }
    return $providerId;
}
//根据身份标签获取该服务商区域id
function getProviderAreaId()
{
    $providerId =  getProviderId();
    $ProviderAreaId = Db::name('member')->where(array('memberId'=>$providerId,'memberType'=>1))->value('areaId');
    return $ProviderAreaId;
}
function pwd_hash($password)
{
    return hash("md5",hash("sha256", trim($password)));
}
//根据地区id获取地区名称
function getAreaName($id)
{
    return Db::name('area')->where('areaId',$id)->value('areaName');
}
//平台联系人 电话
function getPlatform()
{
    $provider['providerName']="龙飞";
    $provider['mobile']=18611398788;
    return $provider;
}
//客服电话
function getServiceTel()
{
    $id=getProviderId();
    return Db::name('member')->where('memberId',$id)->value('mobile');
}
//底部链接
function getFooter()
{
    $providerId=getProviderId();
    //文章 了解我们
    $understandCategoryId=Db::name('article_category')->where('categoryName',"了解我们")->value('articleCategoryId');

    if(empty($understandCode)){
        $understandCode=Db::name('article')->where('providerId',0)->where('articleCategoryId',$understandCategoryId)->where('passId',1)->value('templateCode');
    }else{
        $understandCode=Db::name('article')->where('providerId',$providerId)->where('articleCategoryId',$understandCategoryId)->where('passId',1)->value('templateCode');
    }
    //文章 联系我们
    $relationCategoryId=Db::name('article_category')->where('categoryName',"联系我们")->value('articleCategoryId');

    if(empty($relationCode)){
        $relationCode=Db::name('article')->where('providerId',0)->where('articleCategoryId',$relationCategoryId)->where('passId',1)->value('templateCode');
    }else{
        $relationCode=Db::name('article')->where('providerId',$providerId)->where('articleCategoryId',$relationCategoryId)->where('passId',1)->value('templateCode');
    }
    //文章 常见问题
    $problemCategoryId=Db::name('article_category')->where('categoryName',"常见问题")->value('articleCategoryId');

    if(empty($problemCode)){
        $problemCode=Db::name('article')->where('providerId',0)->where('articleCategoryId',$problemCategoryId)->where('passId',1)->value('templateCode');
    }else{
        $problemCode=Db::name('article')->where('providerId',$providerId)->where('articleCategoryId',$problemCategoryId)->where('passId',1)->value('templateCode');
    }

    //文章 退款说明
    $refundCategoryId=Db::name('article_category')->where('categoryName',"退款说明")->value('articleCategoryId');

    if(empty($refundCode)){
        $refundCode=Db::name('article')->where('providerId',0)->where('articleCategoryId',$refundCategoryId)->where('passId',1)->value('templateCode');
    }else{
        $refundCode=Db::name('article')->where('providerId',$providerId)->where('articleCategoryId',$refundCategoryId)->where('passId',1)->value('templateCode');
    }

    //文章 购买流程
    $buyCategoryId=Db::name('article_category')->where('categoryName',"购买流程")->value('articleCategoryId');

    if(empty($buyCode)){
        $buyCode=Db::name('article')->where('providerId',0)->where('articleCategoryId',$buyCategoryId)->where('passId',1)->value('templateCode');
    }else{
        $buyCode=Db::name('article')->where('providerId',$providerId)->where('articleCategoryId',$buyCategoryId)->where('passId',1)->value('templateCode');
    }
    $code['understandCode']=$understandCode;
    $code['relationCode']=$relationCode;
    $code['problemCode']=$problemCode;
    $code['refundCode']=$refundCode;
    $code['buyCode']=$buyCode;
    return $code;

}
//生成时间
function aTime(){
    date_default_timezone_set('PRC'); // 中国时区
    return date('Y-m-d H:i:s');
}

//发送邮箱验证码
 function sendEmail($emailCode,$toemail,$title,$content)
{
//获取邮箱配置信息
    $Host =   Db::name('param')->where(array('paramCode'=>'MAIL_SMTP_URL'))->value('paramValue');;
    $Username =   Db::name('param')->where(array('paramCode'=>'SERVICE_TEL'))->value('paramValue');;
    $Password =   Db::name('param')->where(array('paramCode'=>'MAIL_PASSWORD'))->value('paramValue');;
    $mail = new PHPMailer();
    $mail->isSMTP();// 使用SMTP服务
    $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
    $mail->Host = $Host;// 发送方的SMTP服务器地址
    $mail->SMTPAuth = true;// 是否使用身份验证
    $mail->Username = $Username;// 发送方的QQ邮箱用户名，就是自己的邮箱名
    $mail->Password = $Password;// 发送方的邮箱密码，不是登录密码,是qq的第三方授权登录码,要自己去开启,在邮箱的设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 里面
    $mail->SMTPSecure = "ssl";// 使用ssl协议方式,
    $mail->Port = 465;// QQ邮箱的ssl协议方式端口号是465/587

    $mail->setFrom($Username,"企业宝");// 设置发件人信息，如邮件格式说明中的发件人,
    $mail->addAddress($toemail,'验证码');// 设置收件人信息，如邮件格式说明中的收件人
    $mail->addReplyTo("qyb@qybao.com.cn","Reply");// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址
    $mail->Subject = $title;// 邮件标题
    $mail->Body = $content;// 邮件正文
    //$mail->AltBody = "This is the plain text纯文本";// 这个是设置纯文本方式显示的正文内容，如果不支持Html方式，就会用到这个，基本无用

    if(!$mail->send()){// 发送邮件
        $res['code'] =  'fail';
        $res['msg']  = "发送失败";// 输出错误信息
      //  $res['msg']  = "Mailer Error: ".$mail->ErrorInfo;// 输出错误信息
    }else{
        Session::set($toemail.'_emailCode',$emailCode);
        Session::set($toemail.'_sendTime',time());
        $res['code'] =  'ok';
        $res['msg']  = '发送成功';// 输出信息
    }
    return $res;
}
//登录用户手机号前三位,后四位
function mobile(){
    $Login_userId=  Session::get('Login_userId');
    $where=array(
        'memberId' => $Login_userId,
    );
    $user =   Db::name('member')->where($where)->find();
    $rew['phonefont'] =  substr($user['mobile'],0,3);
    $rew['phoneback'] =  substr($user['mobile'],-4);
    $rew['emailfontk']  =  substr($user['email'],0,4);
    //@出现位置
    //长度
    $strlen =   strlen($user['email']);
    $wei  = strpos($user['email'],"@");
    $rew['emailback']  =  substr($user['email'],$wei,$strlen);
    return $rew;

}
//图片路径
function filepath($fileId){
   return  Db::name('files')->where(array('filesId' =>$fileId))->value('thumbFile');
}
function canUse($memberId){
    //服务商id
    $providerId  = getProviderId();
    $nowTime =  time();
    $where =  array(
        'memberId' =>$memberId,
        'providerId'=>$providerId,
        'status' =>0,
    );
    $coupons =  Db::name('buyer_coupon')->where($where)->select();
    if(!empty($coupons)){
        foreach($coupons as  $k=>$v){
           //计算是否过期
         $expiryTime    = strtotime($v['expiryDate']) ;
            if($expiryTime < $nowTime){
                //将过期的优惠券状态修改为 过期
                $where2 = array('buyerCouponId'=>$v['buyerCouponId']);
                Db::name('buyer_coupon')->where($where2)->update(array('status'=>2));
            }
        }
        $canUse =  Db::table('buyer_coupon')
            ->alias('a')
            ->join('coupon w','a.couponId = w.couponId')
            ->where(array('memberId'=>$memberId,'providerId'=>getProviderId(),'status'=>0,'w.isEnable' => 1))
            ->select();
        foreach($canUse  as $k => $v){
           if($v['categoryId']  == 0){
               $canUse[$k]['categoryName'] ='全品';
               $addDateTime =   Db::name('buyer_coupon')->where(array('buyerCouponId'=>$v['buyerCouponId']))->value('addDateTime');
               $canUse[$k]['formTime'] =$addDateTime;
           }else{
              $categoryName =  Db::name('service_category')->where(array('serviceCategoryId'=>$v['categoryId']))->value('categoryName');
               $canUse[$k]['categoryName'] =$categoryName;
               $addDateTime =   Db::name('buyer_coupon')->where(array('buyerCouponId'=>$v['buyerCouponId']))->value('addDateTime');
               $canUse[$k]['formTime'] =$addDateTime;
           }
        }
        return $canUse;
    }

}
function welcome(){
    //获取当前用户的余额，头像，手机号，用户名，优惠券，是否有支付密码
    $Login_userId =    Session::get('Login_userId');
    $user =  Db::name('member')->where(array('memberId'=>$Login_userId))->find();
    $account= Db::name('member_account')->where(array('memberId'=>$Login_userId))->find();
    $user['account'] = $account['account'];
    $user['headImgFilePath'] = filepath($user['headImgFileId']);
    //过滤过期的优惠券
    $arr = array(
        'memberId'=>$Login_userId,
        'status'=>0,
        'expiryDate'=>['<',date('y-m-d h:i:s',time())],
        'providerId'=>getProviderId(),
    );
    $arr1 = array(
        'memberId'=>$Login_userId,
        'status'=>0,
        'providerId'=>getProviderId(),
    );
    Db::name('buyer_coupon')->where($arr)->update(array('status' =>2 ));
    $user['coupon'] = Db::name('buyer_coupon')->where($arr1)->count();
    $user['phonefont'] = mobile($Login_userId)['phonefont'];
    $user['phoneback'] = mobile($Login_userId)['phoneback'];
    $user['phoneback'] = mobile($Login_userId)['phoneback'];
    if( $account['tradePwd'] == '' ||  $account['tradePwd'] == null){
        $user['hasTradePwd'] ='no';
    }else{
        $user['hasTradePwd'] ='yes';
    }
    return $user;
}
function createRandomStr(){
    $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
    $strlen = 62;
    while(6 > $strlen){
        $str .= $str;
        $strlen += 62;
    }
    $str = str_shuffle($str);
    return substr($str,0,6);
}
function getInvitationCode(){
    for(;;){
      $invitationCode = createRandomStr();
        $res =   Db::name('member')->where(array('invitationCode'=>$invitationCode))->find();
        if($res == null){
            break;
        }
    }
    return $invitationCode;
}
//精确到秒的时间转换为到日期
function  changdate($date){
   $newdate = date('Y-m-d',strtotime($date));
    return     str_replace('-','.',$newdate);
}
//设置平台连接
function setProviderLink($starLevelLink){
    return "http://". $starLevelLink.".qybao.com.cn";
}
//企业宝客服
function servicetel(){
    return   Db::name('param')->where(array('paramCode'=>'SERVICE_TEL'))->value('paramValue');
}
//订单返现比例
//推荐人比例
function ratio()
{
    return Db::name('param')->where(['paramCode'=>'RECO_MEMBER_SCALE','isEnable'=>1])->value('paramValue');
}
//佣金返现比例
function commission()
{
    return Db::name('param')->where(['paramCode'=>'COMMISSIONS_SCALE','isEnable'=>1])->value('paramValue');
}
//优惠券是否过期
 function  isUse($buyerCouponId){
    //优惠券有效期
    $expire  = Db::name('buyer_coupon')->where('buyerCouponId',$buyerCouponId)->value('expiryDate');
    $nowTime =  time();
    if($nowTime>strtotime($expire)){
        //过期了
        Db::name('buyer_coupon')->where('buyerCouponId',$buyerCouponId)->update(array('status'=>2));
        return 'no';
    }else{
        return 'ok';
    }
}
function getOptionList($menuCode){
    $where1['menuCode'] = ["=", $menuCode];
    $optionList= Db::name('menu so')->join('option sos', 'so.menuId=sos.menuId')->field('sos.optionCode,sos.optionName')->where($where1)->order('serialNo asc')->select();
    return $optionList;
}
//获取操作人账号
function getInputPerson()
{
    return  Session::get('Login_userId');
}
function detailPrice($activPrice){
    if(ceil($activPrice)<10000){
        return $activPrice;
    }elseif ($activPrice>=10000 && $activPrice<100000000){
        if(ceil($activPrice/100)/100==10000){
            return 1 ."亿";
        }else{
            return ceil($activPrice/100)/100 ."万";
        }

    }elseif ($activPrice>=100000000){
        return ceil($activPrice/1000000)/100 ."亿";
    }
}

